<?php
/**
 * Created by PhpStorm.
 * User: yuyiwen
 * Date: 2018/10/12
 * Time: 上午11:18
 */

namespace app\admin\controller;
use think\Request;


class Role extends Common
{
    public function index () {
        $search = input('get.search' , '' , 'htmlspecialchars');
        $page_search = $search;
        $role = db('role');
        if ($search){

            $search = '%'.$search.'%';


            $where = '';
            $where .= ' `name` LIKE "'.$search;

            $role->where($where);

        }
        $role_list = $role->paginate(2 , false , ['query'=>['search'=>$page_search]]);

        $current_page = input('get.page' , 1 , 'intval');

        $page = $role_list->render();
        $page = str_replace(
            ['class="pagination"' , 'class="disabled"' , 'class="active"'],
            ['class="am-pagination tpl-pagination"' , 'class="am-disabled"' , 'class="am-active"'],
            $page
        );
        $request = Request::instance();
        if ( $request->isAjax() )
        {
            return json(['role_list' => $role_list  , 'page' => $page , 'current_page'=>$current_page]);
        }
        $this->assign('page' , $page);
        $this->assign('current_page' , $current_page);
        $this->assign('role_list' , $role_list);
        return view();
    }
    // 编辑角色权限
    public function rolepermissionedit () {
        $roleId = input('get.id');
        $role = db('role')->find($roleId);


        # 查询所有权限
        $permission = db('permission')->order('ords')->select();
        $permission = rebuildArr2($permission);

        # 查询当前角色所拥有的权限
        $permissions_id = db('RolePermission')->where('role_id' , $roleId)->select();
        $having_permissions_id = [];
        foreach ($permissions_id as $key => $value)
        {
            $having_permissions_id[] = $value['permission_id'];
        }


        $this->assign('having_permissions_id',$having_permissions_id);
        $this->assign('permission' , $permission);
        $this->assign('role' , $role);
        return view();
    }

    public function rolepermissionstore ()
    {
        $post = input('post.');
        db('RolePermission')->where('role_id' , $post['role_id'])->delete();

        foreach ($post['permission_id'] as $key => $value) {
            $insertData = ['role_id' => $post['role_id'] , 'permission_id' => $value];
            db('RolePermission')->insert($insertData);
        }
        $this->success('修改成功', url('index'));
    }
}